<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="商品名称" prop="prodName">
        <el-input
          v-model="queryParams.prodName"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['product:prod:add']"
          >新增</el-button
        >
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['product:prod:edit']"
          >修改</el-button
        >
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['product:prod:remove']"
          >删除</el-button
        >
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['product:prod:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="prodList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" width="55" prop="prodId" />
      <el-table-column label="SPU" align="center" width="80" prop="prodSpu" />
      <el-table-column label="商品类型" align="center" prop="prodKind">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.sys_prod_kind"
            :value="scope.row.prodKind"
          />
        </template>
      </el-table-column>
      <el-table-column label="商品分类" align="center" prop="typeName" />
      <el-table-column label="商品名称" align="center" prop="prodName" />
      <el-table-column label="商品品牌" align="center" prop="brandId">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.sys_prod_brand"
            :value="scope.row.brandId"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="150"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品单位" align="center" prop="unitId">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.sys_prod_unit"
            :value="scope.row.unitId"
          />
        </template>
      </el-table-column>
      <el-table-column label="商品标签" align="center" prop="tagId">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.sys_prod_tag"
            :value="scope.row.tagId"
          />
        </template>
      </el-table-column>
      <el-table-column label="供应商" align="center" prop="appr" />
      <el-table-column
        label="缩略图"
        align="center"
        prop="prodImage"
        width="100"
      >
        <template slot-scope="scope">
          <image-preview
            v-if="scope.row.prodImage"
            :src="scope.row.prodImage"
            :width="50"
            :height="50"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="280"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['product:prod:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['product:prod:remove']"
            >删除</el-button
          >

          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleAttaShow(scope.row)"
            v-hasPermi="['product:prod:edit']"
            >附件</el-button
          >

          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleProdInfo(scope.row)"
            v-hasPermi="['product:prod:edit']"
            >明细</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品名称" prop="prodName">
          <el-input v-model="form.prodName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="SPU" prop="prodSpu">
          <el-input v-model="form.prodSpu" placeholder="请输入SPU" />
        </el-form-item>
        <el-form-item label="商品类型" prop="prodKind">
          <el-select v-model="form.prodKind" placeholder="请选择商品类型">
            <el-option
              v-for="dict in dict.type.sys_prod_kind"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="商品分类" prop="prodType">
          <el-cascader
            :options="typeList"
            :props="cascaderProps"
            :show-all-levels="false"
            v-model="form.prodType"
          ></el-cascader>
        </el-form-item>

        <el-form-item label="商品单位" prop="unitId">
          <el-select v-model="form.unitId" placeholder="请选择商品单位">
            <el-option
              v-for="dict in dict.type.sys_prod_unit"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="商品品牌" prop="brandId">
          <el-select v-model="form.brandId" placeholder="请选择商品品牌">
            <el-option
              v-for="dict in dict.type.sys_prod_brand"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="商品标签" prop="tagId">
          <el-select v-model="form.tagId" placeholder="请选择商品标签">
            <el-option
              v-for="dict in dict.type.sys_prod_tag"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="供应商" prop="appr">
          <el-input v-model="form.appr" placeholder="请输入供应商" />
        </el-form-item>
        <el-form-item label="缩略图" prop="prodImage">
          <image-upload v-model="form.prodImage" :limit="1" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!--商品附件添加-->
    <div>
      <el-dialog title="添加商品附件" :visible.sync="dialogFormVisible">
        <el-form :model="formAtta">
          <el-form-item label="轮播图" :label-width="formLabelWidth">
            <image-upload v-model="formAtta.attaImages"></image-upload>
          </el-form-item>

          <el-form-item label="商品视频" :label-width="formLabelWidth">
            <file-upload v-model="formAtta.attaVideo"></file-upload>
          </el-form-item>

          <el-form-item label="定时上架" :label-width="formLabelWidth">
            <el-switch
              v-model="formAtta.upFlag"
              active-text="定时上架"
              inactive-text="立即上架"
              :active-value="1"
              :inactive-value="0"
            >
            </el-switch>
          </el-form-item>
          <el-form-item
            label=""
            v-if="formAtta.upFlag == 1"
            :label-width="formLabelWidth"
          >
            <el-date-picker
              v-model="formAtta.upTime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期时间"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="定时下架" :label-width="formLabelWidth">
            <el-switch
              v-model="formAtta.downFlag"
              active-text="定时下架"
              inactive-text="立即下架"
              :active-value="1"
              :inactive-value="0"
            >
            </el-switch>
          </el-form-item>
          <el-form-item
            label=""
            v-if="formAtta.downFlag == 1"
            :label-width="formLabelWidth"
          >
            <el-date-picker
              v-model="formAtta.downTime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期时间"
            >
            </el-date-picker>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="onSubmitAtta()">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  listProd,
  getProd,
  delProd,
  addProd,
  updateProd,
  addAtta,
  listFromEs,
} from "@/api/product/prod";
import { listType } from "@/api/product/type";

export default {
  name: "Prod",
  dicts: [
    "sys_prod_unit",
    "sys_prod_kind",
    "sys_prod_type",
    "sys_prod_tag",
    "sys_prod_brand",
  ],
  data() {
    return {
      //弹出框
      dialogFormVisible: false,
      formLabelWidth: "120px",
      //商品附件信息
      formAtta: {},
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品管理表格数据
      prodList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        prodSpu: null,
        prodKind: null,
        prodType: null,
        prodName: null,
        brandId: null,
      },
      // 表单参数
      form: {},
      // 商品分类树组
      typeList: [],
      cascaderProps: {
        label: "typeName", // 指定选项标签为 name 字段
        value: "typeId", // 指定选项值为 id 字段
        children: "children", // 指定子选项为 children 字段
        checkStrictly: true,
      },
      // 表单校验
      rules: {
        prodSpu: [{ required: true, message: "SPU不能为空", trigger: "blur" }],
        prodKind: [
          { required: true, message: "商品类型不能为空", trigger: "change" },
        ],
        prodType: [
          { required: true, message: "商品分类不能为空", trigger: "change" },
        ],
        prodName: [
          { required: true, message: "商品名称不能为空", trigger: "blur" },
        ],
        unitId: [
          { required: true, message: "商品单位不能为空", trigger: "change" },
        ],
        tagId: [
          { required: true, message: "商品标签不能为空", trigger: "change" },
        ],
      },
    };
  },
  created() {
    // 获取商品列表
    this.getList();
    // 获取商品分类树组
    this.getTypeTree();
  },
  methods: {
    /**商品详情*/
    handleProdInfo(row) {
      //sessionStorage.setItem("prodId", row.prodId);
      console.log("prodId", row.prodId);
      //跳转
      this.$router.push(`/product/prod/detail/${row.prodId}`);
    },
    /**商品添加附件 */
    handleAttaShow(row) {
      this.formAtta = {};
      this.formAtta.prodId = row.prodId;
      this.dialogFormVisible = true;
    },
    onSubmitAtta() {
      addAtta(this.formAtta).then((res) => {
        if (res.code == 200) {
          this.$modal.msgSuccess("商品附件添加成功");
          this.dialogFormVisible = false;
        } else {
          this.$modal.msgError(res.msg);
        }
      });
    },
    /** 查询商品分类列表 */
    getTypeTree() {
      let param = {
        pageNum: 1,
        pageSize: 99999,
      };
      listType(param).then((response) => {
        this.typeList = this.handleTree(response.data, "typeId", "typePid");
        console.log("typeList", this.typeList);
      });
    },
    /** 查询商品管理列表 */
    getList() {
      this.loading = true;
      listFromEs(this.queryParams).then((response) => {
        this.prodList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        prodId: null,
        prodSpu: null,
        prodKind: null,
        prodType: null,
        prodName: null,
        brandId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        unitId: null,
        tagId: null,
        appr: null,
        prodImage: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.prodId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const prodId = row.prodId || this.ids;
      getProd(prodId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改商品管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.prodType.length > 0) {
            this.form.prodType =
              this.form.prodType[this.form.prodType.length - 1];
          }
          if (this.form.prodId != null) {
            updateProd(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProd(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const prodIds = row.prodId || this.ids;
      this.$modal
        .confirm("您确认要删除吗？删除后不可以恢复！")
        .then(function () {
          return delProd(prodIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "product/prod/export",
        {
          ...this.queryParams,
        },
        `prod_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
